<template>
	<div class="div1">
		<el-breadcrumb separator="/">
			<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>咨询师管理</el-breadcrumb-item>
		</el-breadcrumb>
	</div>
	<div>
		<div class="div2">
			<span class="spanTop">咨询师名称</span>
			<el-input size="large" v-model="searchName" style="width: 240px" placeholder="请输入咨询师名称" clearable />
			<span class="spanTop">咨询师等级</span>
			<el-select v-model="searchCounselorLevelName" placeholder="请选择咨询师等级" size="large" style="width: 240px"
				filterable allow-create default-first-option>
				<el-option value="" label=""></el-option>
				<el-option v-for="(item,index) in AllCounselorLevel" :value="item.id" :label="item.name" />
			</el-select>
			<span class="spanTop">地址</span>
			<el-input size="large" v-model="searchAddress" style="width: 240px" placeholder="请输入地址" clearable />
			<span class="spanTop">手机号</span>
			<el-input size="large" v-model="searchPhone" style="width: 240px" placeholder="请输入手机号" clearable />
		</div>
		<el-button @click="query" type="primary" size="large" class="bt1">搜索</el-button>
		<el-button type="primary" @click="createOrUpdate('')" size="large" class="bt1">新增咨询师</el-button>
		<el-button type="danger" size="large" class="bt1" @click="removeAll">批量删除</el-button>
		<el-table :data="tableData" style="width: 100%;margin-top: 10px;" border
			@selection-change="handleSelectionChange">
			<el-table-column type="selection" />
			<el-table-column fixed prop="id" label="ID" />
			<el-table-column prop="name" label="咨询师名称" />
			<el-table-column prop="counselorGrade.name" label="咨询师等级" />
			<el-table-column prop="sex" label="性别" />
			<el-table-column prop="mobile" label="手机号" />
			<el-table-column prop="email" label="邮箱" />
			<el-table-column label="头像">
				<template #default="scope">
					<el-avatar shape="square" size="large" :src="'http://localhost:8080'+ scope.row.profile" />
				</template>
			</el-table-column>
			<el-table-column label="证书图片">
				<template #default="scope">
					<el-avatar shape="square" size="large" :src="'http://localhost:8080'+ scope.row.credential" />
				</template>
			</el-table-column>
			<el-table-column prop="address" label="所属地址" />
			<el-table-column prop="description" label="咨询师简介" />
			<el-table-column label="职位">
				<template #default="scope">
					<div class="counselorPostsOne" v-if="scope.row.position==1">咨询师</div>
					<div class="counselorPostsTwo" v-else>心理导师</div>
				</template>
			</el-table-column>

			<el-table-column fixed="right" label="操作" width="200">
				<template #default="scope">
					<el-button type="primary" @click="createOrUpdate(scope.row)">编辑</el-button>
					<el-button type="danger" @click="remove(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-dialog v-model="dialogFormVisible" :title="form.id.length==0?'新增咨询师':'编辑咨询师'" width="800"
			style="margin-bottom: 60px;" @close="handleClose">
			<el-form>
				<el-form-item label="咨询师名称" :label-width="formLabelWidth">
					<el-input size="large" v-model="form.name" autocomplete="off" placeholder="请输入咨询师名称" />
				</el-form-item>

				<el-form-item label="咨询师等级" :label-width="formLabelWidth" style="clear: left;">
					<el-select v-model="form.gradeId" placeholder="请选择咨询师等级" size="large" style="width: 240px"
						filterable allow-create default-first-option>
						<el-option value="" label=""></el-option>
						<el-option v-for="(item,index) in AllCounselorLevel" :value="item.id" :label="item.name" />
					</el-select>
				</el-form-item>
				<el-form-item label="咨询师性别" :label-width="formLabelWidth">
					<!-- 单选组：绑定表单字段，男篮/女粉选项 -->
					<el-radio-group v-model="form.sex" size="large" class="category-radio">
						<!-- 男篮选项：未选文本蓝，选中背景蓝 -->
						<el-radio-button label="男" value="男" class="men-basketball" />
						<!-- 女粉选项：未选文本粉，选中背景粉 -->
						<el-radio-button label="女" value="女" class="women-fans" />
					</el-radio-group>
				</el-form-item>
				<el-form-item label="手机号" :label-width="formLabelWidth">
					<el-input size="large" v-model="form.mobile" autocomplete="off" placeholder="请输入手机号" />
				</el-form-item>
				<el-form-item label="邮箱" :label-width="formLabelWidth">
					<el-input size="large" v-model="form.email" autocomplete="off" placeholder="请输入邮箱" />
				</el-form-item>
				<el-form-item label="头像" :label-width="formLabelWidth">

					<el-upload action="http://localhost:8080/upload" list-type="picture-card"
						:on-success="handleSuccessProfile" :limit="1" :on-preview="handlePictureCardPreview"
						:file-list="fileList" :on-remove="handleRemoveProfile">
						<el-icon style="width: 128px; height: 128px;border: 1px
					dashed #DCDFE6; border-radius: 5px;font-size: 20px;">
							<Plus />
						</el-icon>
					</el-upload>
					<!-- 放大预览组件: 和官网一致 -->
					<el-dialog v-model="dialogVisible">
						<img w-full :src="dialogImageUrl" alt="Preview Image" />
					</el-dialog>
				</el-form-item>
				<el-form-item label="证书图片" :label-width="formLabelWidth">
					<el-avatar shape="square" size="large" :src="'http://localhost:8080'+ form.credential" />
					<el-upload action="http://localhost:8080/upload" list-type="picture-card"
						:on-success="handleSuccessCredential" :limit="1" :on-preview="handlePictureCardPreview"
						:file-list="fileList" :on-remove="handleRemoveCredential">
						<el-icon style="width: 128px; height: 128px;border: 1px
					dashed #DCDFE6; border-radius: 5px;font-size: 20px;">
							<Plus />
						</el-icon>
					</el-upload>
					<!-- 放大预览组件: 和官网一致 -->
					<el-dialog v-model="dialogVisible">
						<img w-full :src="dialogImageUrl" alt="Preview Image" />
					</el-dialog>
				</el-form-item>
				<el-form-item label="所属地址" :label-width="formLabelWidth">
					<el-input size="large" v-model="form.address" autocomplete="off" placeholder="请上传所属地址" />
				</el-form-item>
				<el-form-item label="咨询师简介" :label-width="formLabelWidth">
					<el-input size="large" v-model="form.description" autocomplete="off" placeholder="请上传咨询师简介" />
				</el-form-item>
				<el-form-item label="咨询师分类" :label-width="formLabelWidth" style="clear: left;">
					<el-select v-model="form.position" placeholder="请选择咨询师分类" size="large" style="width: 240px">
						<el-option :value="1" label="咨询师" />
						<el-option :value="2" label="心理导师" />
					</el-select>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="dialogFormVisible = false">取消</el-button>
					<el-button @click="dialogFormVisible = false,add()">
						确定
					</el-button>
				</div>
			</template>
		</el-dialog>
		<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10,15, 20]"
			:size="size" layout="total, sizes, prev, pager, next, jumper" :total=" total"
			@size-change="handleSizeChange" @current-change="handleCurrentChange" v-if="total !=0" />
	</div>
</template>
<script setup>
	import {
		onMounted,
		ref,
		reactive,
		computed,
		watch
	} from 'vue'
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	import {
		Plus
	} from '@element-plus/icons-vue'
	import {
		getCurrentInstance
	} from 'vue';

	const axios = getCurrentInstance().appContext.config.globalProperties.axios
	const tableData = ref([])
	const currentPage = ref(1) // 当前页
	const pageSize = ref(5) // 每页显示条目数
	const size = 'default' // 分页大小
	const total = ref(0)
	const searchName = ref('')
	const searchCounselorLevelName = ref('')
	const searchAddress = ref('')
	const searchPhone = ref('')

	const form = ref({
		id: '',
		name: '',
		gradeId: 1,
		mobile: "",
		email: "",
		profile: "",
		sex: "男",
		credential: "/20250712/93a4a04b-8fd5-4594-bc90-71f1f9c44f49.png",
		address: "",
		description: "",
		position: 1,
		counselorGrade: {
			id: 1,
			name: "国家一级咨询师",
		}
	})

	const dialogFormVisible = ref(false)
	const formLabelWidth = '100px'
	const AllCounselorLevel = ref([])

	const getAllCounselorLevel = () => {
		axios.get('counselorGrade', ).then((resp) => {
			console.log(resp.data);
			AllCounselorLevel.value = resp.data
		});
	}
	// 图片上传
	const dialogImageUrl = ref('') // 图片预览框的地址
	const dialogVisible = ref(false) // 控制图片预览框是否显示
	const fileList = ref([])
	// 上传成功的回调，res服务器响应的数据
	const handleSuccessProfile = (res, file) => {
		console.log("图片上传成功", res)
		/*
		多图片上传：
		1、如果数据库是单字段，把多个图片的名称适用,分隔，拼接成一个字符串
		1.jpg,2.jpg
		this.addOrUpdateData.listView += res.data
		2、如果数据库定义了表，专门用来存储图片
		this.addOrUpdateData.listView.push(res.data)
		*/
		form.value.profile = res.data; // res.data就是图片上传的地址
	}
	// 处理删除图片
	const handleRemoveProfile = (file, fileList) => {
		form.value.profile = ''
	}
	const handleSuccessCredential = (res, file) => {
		console.log("图片上传成功", res)
		/*
		多图片上传：
		1、如果数据库是单字段，把多个图片的名称适用,分隔，拼接成一个字符串
		1.jpg,2.jpg
		this.addOrUpdateData.listView += res.data
		2、如果数据库定义了表，专门用来存储图片
		this.addOrUpdateData.listView.push(res.data)
		*/
		form.value.credential = res.data; // res.data就是图片上传的地址
	}
	// 处理删除图片
	const handleRemoveCredential = (file, fileList) => {
		form.value.credential = ''
	}
	// 处理图片预览
	const handlePictureCardPreview = (file) => {
		dialogImageUrl.value = file.url;
		dialogVisible.value = true;
	}

	function query() {
		axios.get(
			`counselor/page?name=${searchName.value}&gradeId=${searchCounselorLevelName.value}&address=${searchAddress.value}&mobile=${searchPhone.value}&pageNum=${currentPage.value}&pageSize=${pageSize.value}`,
		).then(resp => {
			tableData.value = resp.data.list;
			total.value = resp.data.total
			console.log(resp);
		})
	}

	const handleSizeChange = (val) => {
		pageSize.value = val;
		query();
	}
	const handleCurrentChange = (val) => {
		currentPage.value = val
		query();
	}
	const handleClose = () => {
		form.value = {
			id: '',
			name: '',
			gradeId: 1,
			mobile: "",
			email: "",
			profile: "",
			sex: "男",
			credential: "/20250712/93a4a04b-8fd5-4594-bc90-71f1f9c44f49.png",
			address: "",
			description: "",
			position: 1,
			counselorGrade: {
				id: 1,
				name: "国家一级咨询师",
			}
		}
	}
	const createOrUpdate = (row) => {
		dialogFormVisible.value = true
		if (row != '') {
			axios.get(`counselor/${row.id}`).then((resp) => {
				console.log('点击编辑得到的：', resp);
				form.value = resp.data
			})
			// getAllCounselorLevel()
		} else {
			console.log('点击新增');
		}
	}
	const add = () => {
		console.log("新增的id", form.value.id);
		if (form.value.id.length === 0) {
			axios.post('/counselor', {
				address: form.value.address,
				credential: form.value.credential,
				email: form.value.email,
				description: form.value.description,
				sex: form.value.sex,
				gradeId: form.value.gradeId,
				name: form.value.name,
				mobile: form.value.mobile,
				position: form.value.position,
				profile: form.value.profile,
				id: '',
			}).then((resp) => {
				console.log('触发新增请求', resp);
				if (resp.data.code == 200) {
					ElMessage({
						message: '新增成功',
						type: 'success',
					})
				} else {
					ElMessage.error('新增失败')
				}
			}).finally(() => {
				query();
			});
		} else {
			axios.put('counselor', {
				address: form.value.address,
				credential: form.value.credential,
				email: form.value.email,
				description: form.value.description,
				gradeId: form.value.gradeId,
				sex: form.value.sex,
				name: form.value.name,
				mobile: form.value.mobile,
				position: form.value.position,
				profile: form.value.profile,
				id: form.value.id,
			}).then((resp) => {
				console.log('触发修改请求', resp);
				if (resp.data.code == 200) {
					ElMessage({
						message: '修改成功',
						type: 'success',
					})
				} else {
					ElMessage.error('修改失败')
				}
			}).finally(() => {
				query();
			});
		}
	}
	const remove = (row) => {
		console.log('当前行的数据', row);
		ElMessageBox.confirm(
				'此操作将永久删除该文件, 是否继续?',
				'Warning', {
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'warning',
				}
			)
			.then(() => {
				axios.delete(`counselor/${row.id}`).then((resp) => {
					console.log('删除后：', resp);
					if (resp.data.code == 200) {
						ElMessage({
							message: '删除成功',
							type: 'success',
						})
					} else {
						ElMessage.error('删除失败')
					}
				}).finally(() => {
					query();
				});

			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '取消删除',
				})
			})

	}
	const multipleSelection = ref([])
	const handleSelectionChange = (val) => {
		multipleSelection.value = val.map(item => {
			return item.id
		})
		console.log(multipleSelection.value);
	}
	const removeAll = (row) => {
		console.log('当前行的数据', row);
		ElMessageBox.confirm(
				'此操作将永久删除该文件, 是否继续?',
				'Warning', {
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'warning',
				}
			)
			.then(() => {
				axios.delete(`counselor`, {
					params: {
						ids: multipleSelection.value.join(',')
					}
				}).then(resp => {
					if (resp.code == 200) {
						ElMessage({
							message: '删除成功',
							type: 'success',
						})
					} else {
						ElMessage.error('删除失败')
					}
				}).finally(() => {
					query();
				});
			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '取消删除',
				})
			})
	}
	onMounted(() => {
		query();
		getAllCounselorLevel();
	})
</script>
<style scoped>
	.counselorPostsOne {
		width: 78px;
		background-color: #ecf5ff;
		border: 1px solid #d9ecff;
		color: #44a0ff;
		text-align: center;
		border-radius: 5px;
		padding: 5px 10px;
	}

	.counselorPostsTwo {
		width: 78px;
		background-color: #fef0f0;
		border: 1px solid #fde2e2;
		color: #f56d6d;
		text-align: center;
		border-radius: 5px;
		padding: 5px 10px;
	}

	.spanTop {
		margin: 0 10px;
		color: #696a6e;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}

	.bt1 {
		margin-top: 10px;
		margin-left: 10px;
	}

	.div1 {
		border-bottom: 1px solid #eeeeee;
		width: 100%;
		height: 30px;
		padding-top: 15px;
		padding-left: 15px;
	}

	.div2 {
		padding-top: 15px;
	}

	.el-table {
		margin-left: 10px;
	}

	.el-pagination {
		margin-top: 10px;
		margin-left: 10px;
	}

	/* 男篮选项样式 */
	.category-radio>>>.men-basketball .el-radio-button__inner {
		/* 未选中：文本蓝色（体育蓝，有活力） */
		color: #165DFF;
	}

	.category-radio>>>.men-basketball.is-checked .el-radio-button__inner {
		/* 选中：背景蓝色，文本白色（对比强烈） */

		color: white;
	}

	/* 女粉选项样式 */
	.category-radio>>>.women-fans .el-radio-button__inner {
		/* 未选中：文本粉色（柔和粉，不刺眼） */
		color: #FF5C8A;
	}

	.category-radio>>>.women-fans.is-checked .el-radio-button__inner {
		/* 选中：背景粉色，文本白色（清晰可见） */

		color: white;
	}
</style>